package com.mifengs.mall.ui.login;


import android.text.TextUtils;
import android.widget.Toast;

import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.mall.MallApplication;
import com.mifengs.mall.event.LoginEvent;
import com.mifengs.mall.netWork.NetWork;
import com.tencent.android.tpush.XGPushConfig;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.ResponseBody;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by lihaoqi on 2017/11/17.
 */

public class RegisterPresent implements RegisterContract.Presenter{

    private final RegisterContract.View mView;

    public RegisterPresent(RegisterContract.View registerView) {
        this.mView = registerView;
    }

    @Override
    public void register() {
        String pwd = mView.getPwd();
        String phone = mView.getPhone();
        String code = mView.getCode();
        String phoneCode = mView.getPhotoCode();
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("nickName",phone);
        hashMap.put("mobile",phone);
        hashMap.put("usertoken", XGPushConfig.getToken(mView.getContext()));
        hashMap.put("password",pwd);
        hashMap.put("randNum",phoneCode);
        hashMap.put("mobileCode",code);
        hashMap.put("mobiletype","1");
        String shareId = mView.getShareId();
        if(!TextUtils.isEmpty(shareId)){
            hashMap.put("shareCode",shareId);
        }
        mView.showLoading();
        NetWork.getRegisterApi().register(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.hideLoading();
                        mView.showNetError();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        mView.hideLoading();
                        try {
                            String result = responseBody.string();
                            JSONObject jsonObject = new JSONObject(result);
                            if (jsonObject.getString("status").equals("0000")) {
                                String hxName ="mfsc"+mView.getPhone().substring(3,mView.getPhone().length());
                                PreferenceUtils.saveHxUserName(MallApplication.getInstance(),hxName);
                                PreferenceUtils.saveHxUserPwd(MallApplication.getInstance(),"mifengs");
                                PreferenceUtils.saveUserMobile(MallApplication.getInstance(),mView.getPhone());
                                JSONObject loginToken = jsonObject.getJSONObject("paramer");
                                String token = loginToken.getString("loginToken");
                                PreferenceUtils.saveToken(token);
                                mView.showLongToast("注册并登录成功，尽情的购物去吧！");
                                EventBus.getDefault().post(new LoginEvent(LoginEvent.LOGIN_SUCCESS));
                                mView.finish();
                            } else{
                                ToastUitl.show(jsonObject.getString("info"), Toast.LENGTH_SHORT);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
//
                    }
                });
    }

    @Override
    public void sendSMSCode() {
         String phone = mView.getPhone();
        String randNum = mView.getPhotoCode();
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("randNum",randNum);
        hashMap.put("mobile",phone);
        mView.showLoading();
        NetWork.getRegisterApi().sendSMSCode(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.<ResponseBody>bindToLife())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.hideLoading();
                        mView.showNetError();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        mView.hideLoading();
                        String result = null;
                        try {
                            result = responseBody.string();
                            JSONObject jsonObject = new JSONObject(result);
                            if (jsonObject.getString("status").equals("0000")) {
                                mView.isPhone();
                                ToastUitl.show("验证码发送成功，请注意查收短信", Toast.LENGTH_SHORT);
                            }else{
                                ToastUitl.show(jsonObject.getString("info"), Toast.LENGTH_SHORT);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    @Override
    public void isPhone() {
        String phone = mView.getPhone();
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("mobile",phone);
        NetWork.getRegisterApi().getIsPhone(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mView.<ResponseBody>bindToLife())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showNetError();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        mView.hideLoading();
                        String result = null;
                        try {
                            result = responseBody.string();
                            JSONObject jsonObject = new JSONObject(result);
                            if (jsonObject.getString("status").equals("0000")) {
                                sendSMSCode();
                            }else{
                                ToastUitl.show(jsonObject.getString("info"), Toast.LENGTH_SHORT);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


}
